package com.mamba.microservice.dubbo.filter;

import com.mamba.microservice.context.ContextLogbackUtils;
import com.mamba.microservice.context.ServiceContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.constants.CommonConstants;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import java.util.Map;

/**
 * Copyright ©2020 360jinrong All Rights Reserved
 * 请添加类/接口的说明：初始化消费端的上下文信息
 * 1.透传请求号
 *
 * @Package: com.mamba.microservice.dubbo.filter
 * @author: fangjin
 * @date: 2020年04月22日 10时24分
 */
@Slf4j
@Activate(group = {CommonConstants.CONSUMER}, order = -6000)
public class MmsConsumerContextFilter implements Filter {

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        ServiceContext serviceContext = ServiceContext.getContext();
        try {
            String requestNo = serviceContext.getRequestNo();
            if (StringUtils.isEmpty(requestNo)) {
                serviceContext.setRequestNo();
                requestNo = serviceContext.getRequestNo();
            }
            log.debug("requestNo from context :{}", requestNo);
            /** 将requestNo加入logback MDC 实现日志的分布式追踪*/
            ContextLogbackUtils.addContext2MDC();

            RpcContext rpcContext = RpcContext.getContext();
            Map<String, String> attachments = rpcContext.getAttachments();
            /** 将服务的上下文信息传到下个节点 */
            attachments.putAll(serviceContext.getContextVariables());

            return invoker.invoke(invocation);
        } catch (Exception e) {
            throw e;
        } finally {
            /** 防止内存泄露 */
            serviceContext.clearContextVariables();
            ContextLogbackUtils.removeContextFromMDC();
        }
    }

    @Override
    public Result onResponse(Result appResponse, Invoker<?> invoker, Invocation invocation) {
        return null;
    }
}
